package com.arrogames.blondbattle.game.state 
{
	import ash.core.Engine;
	import ash.core.NodeList;
	import ash.core.System;
	import ash.signals.Signal0;
	import ash.signals.Signal1;
	import com.arrogames.blondbattle.game.combat.Faction;
	import com.arrogames.blondbattle.game.UIEntityCreator;
	import org.as3commons.logging.api.getLogger;
	import org.as3commons.logging.api.ILogger;
	
	/**
	 * Counts the number of bases. If this is reduced to zero for one faction then the game is begin stopped.
	 * If the computer has zero bases, the player wins.
	 * If the player has zero bases, the player loses.
	 * 
	 * @author Robin van den Bogaard
	 */
	public class VictorySystem extends System {
		
		private static const logger:ILogger = getLogger(VictorySystem);
		
		private var uiCreator:UIEntityCreator;
		private var nodes:NodeList;
		
		private var _gameOver:Signal0;
		
		private var gameIsDecided:Boolean;
		
		public function VictorySystem(uiCreator:UIEntityCreator) {
			super();
			gameIsDecided = false;
			this.uiCreator = uiCreator;
			_gameOver = new Signal0();
		}
		
		override public function update(time:Number):void {
			super.update(time);
			if (!gameIsDecided) {
				var node:VictoryNode;
				var humanCount:Number = 0;
				var cpuCount:Number = 0;
				
				for (node = nodes.head; node; node = node.next) {
					if (node.faction.name == Faction.HUMAN) {
						humanCount++;
					} else if (node.faction.name == Faction.COMPUTER) {
						cpuCount++;
					}
				}
				
				if (cpuCount == 0 && humanCount == 0) {
					gameOver.dispatch();
					uiCreator.createDrawGraphic();
					logger.info("Its a draw!");
				} else if (humanCount == 0) {
					uiCreator.createLossGraphic();
					gameOver.dispatch(); //computer wins;
					logger.info("Computer has won!");
				} else if (cpuCount == 0) {
					uiCreator.createWinGraphic();
					gameOver.dispatch(); //computer wins;
					logger.info("Human has won!");
				}
				
				gameIsDecided = cpuCount == 0 || humanCount == 0;
			}
			
		}
		
		override public function addToEngine(engine:Engine):void {
			super.addToEngine(engine);
			
			nodes = engine.getNodeList(VictoryNode);
		}
		
		override public function removeFromEngine(engine:Engine):void {
			super.removeFromEngine(engine);
			
			nodes = null;
			gameOver.removeAll();
		}
		
		public function reset():void {
			gameIsDecided = false;
		}
		
		public function get gameOver():Signal0 {
			return _gameOver;
		}
		
	}

}